<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>进度条 WebSocket 测试</title>
</head>
<body>
<h2>任务进度：</h2>
<progress id="progressBar" value="0" max="100" style="width: 100%; height: 30px;"></progress>
<p id="progressText">0%</p>

<button onclick="startTask()">开始任务</button>

<script>
    let socket = null;

    function startTask() {
        // 防止重复连接
        if (socket && socket.readyState === WebSocket.OPEN) {
            console.log("任务已在进行中");
            return;
        }

        socket = new WebSocket("ws://localhost:8081/ws/progress?task_id=abc123");

        socket.onmessage = function(event) {
            const data = JSON.parse(event.data);  // 解析 JSON 字符串
            const progress = data.progress;       // 取 progress 字段
            document.getElementById("progressBar").value = progress;
            document.getElementById("progressText").innerText = `${progress}%`;
        };

        socket.onclose = function() {
            console.log("任务完成或连接关闭");
        };

        socket.onerror = function() {
            console.log("WebSocket 连接错误");
        };
    }
</script>
</body>
</html>
